<?php
require_once(__PHY_LIB.'/class/Item.class.php');

class CmsWork extends Item {
/// definition and constructor ///
    function CmsWork($id=0, $field="") {
        Query::Query();
        $this->cfgKeyField("id");
        $this->cfgAllField("id,location,rank,work_id,time_added,time_updated");
        $this->cfgTable("cms_work");
        if ("" == $field || "*" == $field) {
            $this->cfgField($this->mAllField);
        }
        else {
            $this->cfgField($field);
        }
        if (0 < $id) {
            $this->cfgWhere($this->mKeyField . "=" . $id);
            $this->load();
        }
        else {
            $this->set($this->mKeyField, $id);
        }
    }

    function invalid() {
        return false;
	}

	/// 排序相关 ///
	function calcNewRank() {
		$sQ = "SELECT MAX(rank) max_rank FROM cms_work WHERE location='".addslashes($this->get('location'))."'";
		$this->loadQuery($sQ);
		$r = $this->nextRecord(false);
		return (int)$r['max_rank'] + 1;
	}
	function rankTo($nRank) {
		if (!(0 < $this->getID())) { return false; }
		$nRank = max(1, (int)$nRank);
		if ($nRank > $this->get('rank')) { // 增大
			$oList = new CmsWorkList();
			$oList->cfgWhere("location='".$this->get('location')."' AND rank>'".$this->get('rank')."' AND rank<='{$nRank}'");
			$oList->load();
			while ($o = $oList->nextItem()) {
				$o->set('rank', $o->get('rank') - 1); // 中间的统统-1
				$o->update();
			}
		}
		elseif ($nRank < $this->get('rank')) { // 减小
			$oList = new CmsWorkList();
			$oList->cfgWhere("location='".$this->get('location')."' AND rank<'".$this->get('rank')."' AND rank>='{$nRank}'");
			$oList->load();
			while ($o = $oList->nextItem()) {
				$o->set('rank', $o->get('rank') + 1); // 中间的统统+1
				$o->update();
			}
		}
		else { // 相等，没变动
			return true;
		}
		/// 修改自己 ///
		$this->set('rank', $nRank);
		$this->update();
		return true;
	}

	function delete() {
		$nMaxRank = $this->calcNewRank() - 1;
		$this->rankTo($nMaxRank);
		return Item::delete();
	}

} /// end class CmsWork.


class CmsWorkList extends ItemList {
    /// definition and constructor ///
    function CmsWorkList($tablename=null) {
        ItemList::ItemList();
        $this->cfgClass("CmsWork");
        $this->cfgKeyField("id");
        $this->cfgAllField("id,location,rank,work_id,time_added,time_updated");
        $this->cfgTable(null == $tablename ? "cms_work" : $tablename);
    }

} /// end class CmsWorkList.


/// related functions ///
?>
